import 'dart:async';

import 'package:flutter/material.dart';
import 'package:projectone/bean/books_bean.dart';
import '../book_detail_pages.dart';
import '../book_type_page.dart';
import '../event_bus.dart';
import '../network_get_data.dart';
import '../link_url.dart';
import 'package:projectone/db_util.dart';
import 'dart:convert';


class BooksList extends StatefulWidget{
  final String str;
  BooksList({Key key,this.str}):super(key: key);
  @override
  _BooksListState createState() {
    // TODO: implement createState
    return _BooksListState();
  }
}
class _BooksListState extends State<BooksList>{
  List<BookTypeBean> bookTypeList=new List();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setState(() {
      bookTypeList=getTypeList();
    });
    //bookTypeList=getTypeList();
  }
  List<BookTypeBean> getTypeList(){
    List<BookTypeBean> retList=new List();
    retList.add(new BookTypeBean('全部',urlApi.baseImgUrl+'/sort/all.html'));
    retList.add(new BookTypeBean('玄幻',urlApi.baseImgUrl+'/sort/xuanhuan.html'));
    retList.add(new BookTypeBean('奇幻',urlApi.baseImgUrl+'/sort/qihuan.html'));
    retList.add(new BookTypeBean('武侠',urlApi.baseImgUrl+'/sort/wuxia.html'));
    retList.add(new BookTypeBean('仙侠',urlApi.baseImgUrl+'/sort/xianxia.html'));
    retList.add(new BookTypeBean('都市',urlApi.baseImgUrl+'/sort/dushi.html'));
    retList.add(new BookTypeBean('历史',urlApi.baseImgUrl+'/sort/lishi.html'));
    retList.add(new BookTypeBean('军事',urlApi.baseImgUrl+'/sort/junshi.html'));
    retList.add(new BookTypeBean('游戏',urlApi.baseImgUrl+'/sort/youxi.html'));
    retList.add(new BookTypeBean('竞技',urlApi.baseImgUrl+'/sort/jingji.html'));
    retList.add(new BookTypeBean('科幻',urlApi.baseImgUrl+'/sort/kehuan.html'));
    retList.add(new BookTypeBean('灵异',urlApi.baseImgUrl+'/sort/lingyi.html'));
    retList.add(new BookTypeBean('同人',urlApi.baseImgUrl+'/sort/tongren.html'));
    retList.add(new BookTypeBean('女生',urlApi.baseImgUrl+'/sort/nvsheng.html'));
    retList.add(new BookTypeBean('其他',urlApi.baseImgUrl+'/sort/qita.html'));
    return retList;
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return GridView.builder(
      gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
          maxCrossAxisExtent: 120.0,
          childAspectRatio: 2.0 //宽高比为2
      ),
      itemCount: bookTypeList.length,
      itemBuilder: (context,i){
        return new Container(
            padding: EdgeInsets.all(10),
            child: MaterialButton(
              color: Colors.white,
              textColor: Colors.grey,
              child: new Text(bookTypeList[i].typeName),
              onPressed: (){
                //点击时间处理，新页面，并且传输 typeUrl 过去
                  Navigator.push(context, MaterialPageRoute(builder:
                  (context){
                    return BookTypePage(bookTypeList[i]);
                  }));
              },
            )
        );
      },
    );
  }
}

/// 书籍推荐页面
class BookRecommend extends StatefulWidget{

  @override
  _RecommendState createState() {
    // TODO: implement createState
    return _RecommendState();
  }
}
class _RecommendState extends State<BookRecommend>{
  List<BooksBean> bookList=new List();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    NetworkData().getBookCommend('a').then((value) =>
    setState((){
      bookList=value;
    })
    );

  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new ListView.builder(
      itemCount: bookList.length,
      itemBuilder: (BuildContext context,int i){
          var bookRecommend=bookList[i];
          return Row(
            children: <Widget>[
              Expanded(child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  new Text('《'+bookRecommend.bookName+'》'),
                  new Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      new Text('作者：'+bookRecommend.author)],

                  ),
                  new Text('最新章节：'+bookRecommend.type),
                  Divider(height: 1,color: Colors.lightBlue,)
                ],
              ),),
              MaterialButton(textColor: Colors.white,color: Colors.lightBlueAccent,
                child: Text('点击查看'),
                onPressed:(){
                  Navigator.push(context, MaterialPageRoute(builder: (context){
                    return BookInfoPage(bookRecommend.bookUrl,bookRecommend.bookName);
              }));
                },)
            ],);
      },);
  }
}

///书架界面
class MyBooksPage extends StatefulWidget{
  @override
  _MyBooksState createState() {
    // TODO: implement createState
    return _MyBooksState();
  }

}
class _MyBooksState extends State<MyBooksPage>{
  List<DBHelpFavoriteBean> list=new List();
  // ignore: cancel_subscriptions
  StreamSubscription streamSubscription;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    DBUtil.dbUtil.getAllBook().then((value) => setState(() {
      list=value;
    }));
    //刷新页面
    streamSubscription=eventBus.on<BookListRefreshEvent>().listen((event){
      if(event.isRefresh){
        DBUtil.dbUtil.getAllBook().then((value) => setState(() {
          list=value;
        }));
      }
    });
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    streamSubscription.cancel();
  }


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    if(list.length==0) return new Center(
      child: new SingleChildScrollView(
        child: new Text('没有找到您的收藏，快去发现新书吧！'),
      ),
    );
    else return new GridView.builder(gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
        maxCrossAxisExtent: 120.0,
        childAspectRatio: 0.5
    ),
        itemCount: list.length,
        itemBuilder: (BuildContext context,int i){
      return GestureDetector(
        onTap: (){
          //点击去阅读界面
          DBHelpFavoriteBean temp=list[i];
          Navigator.push(context, MaterialPageRoute(builder: (context)=> ReadBookPage(temp.book_url,
                    new BookDetailBean.fromJson(json.decode(temp.book_detail_bean)),
                    temp.reading_chapter)),);},
        onLongPress: (){
          //长按去书籍详情
          Navigator.push(context, MaterialPageRoute(builder: (context){
            return BookInfoPage(list[i].book_url,list[i].book_name);
          }));},
        child: Column(
          children: <Widget>[
            Image(image: NetworkImage(list[i].book_cover),width: 90,height: 120,),
            Text(list[i].book_name,maxLines: 1,overflow: TextOverflow.ellipsis,)
          ],
        ),
      );
    });
  }

}